import { NextResponse } from 'next/server'
import { VmsScript,AiScript } from '@/types/Model'
import prisma from '@/lib/prisma'
import { getUser } from '@/lib/authUtils'

export async function PUT(req: Request): Promise<Response> {
  try {
    const userid = await getUser(req)
    if (!userid) {
      return new NextResponse(
        JSON.stringify({ error: '未授权或登录信息过期，请登录' }),
        { status: 401 }
      )
    }
    if (userid instanceof NextResponse) {
      return userid
    }

    const scripts: VmsScript[] = await req.json()

    // 批量更新脚本的psh和pxh
    const updatePromises = scripts.map(async (script) => {
      await prisma.vms_script.update({
        where: { id: script.id },
        data: {
          psh: script.psh,
          pxh: script.pxh
        }
      })
    })

    await Promise.all(updatePromises)

    return new NextResponse(
      JSON.stringify({ message: '脚本顺序更新成功' }),
      { status: 200 }
    )
  } catch (error) {
    console.error('Error updating script order:', error)
    return new NextResponse(
      JSON.stringify({ error: '脚本顺序更新失败' }),
      { status: 500 }
    )
  }
}

export async function POST(req: Request): Promise<Response> {
  try {
    const userid = await getUser(req)
    if (!userid) {
      return new NextResponse(
        JSON.stringify({ error: '未授权或登录信息过期，请登录' }),
        { status: 401 }
      )
    }
    if (userid instanceof NextResponse) {
      return userid
    }

    const scripts: AiScript[] = await req.json()

    // 批量创建脚本
    const createPromises = scripts.map(async (script, index) => {
      await prisma.vms_script.create({
        data: {
          id: crypto.randomUUID(), // 使用crypto生成UUID
          copy_id: script.copy_id,
          plot: script.plot,
          caption: script.caption,
          content: script.content,
          shot_size: script.shot_size,
          shot_angle: script.shot_angle,
          shot_move: script.shot_move,
          location: script.location,
          finished: false,
          psh: index + 1,  // 使用索引+1作为psh
          pxh: index + 1,   // 使用索引+1作为pxh
          user_id:userid
        }
      })
    })
    await prisma.vms_user.update({
      where: { id: userid },
      data: {
        script_count: {
          increment: scripts.length
        }
      }
    })

    await Promise.all(createPromises)

    return new NextResponse(
      JSON.stringify({ message: '脚本批量创建成功' }),
      { status: 200 }
    )
  } catch (error) {
    console.error('Error creating scripts:', error)
    return new NextResponse(
      JSON.stringify({ error: '脚本批量创建失败' }),
      { status: 500 }
    )
  }
}
